/**
 * All Rights Reserved , Copyright (C) 2021 , 青岛鼎信通讯股份有限公司
 *
 *SdProjectHistoryController
 * SD项目立项-历史表
 *
 * 修改纪录
 * 2021-12-06 版本：1.0 wangxinhua 创建。
 * @version 版本：1.0
 * @author 作者：wangxinhua
 * 创建日期：2021-12-06
 */

package com.topscomm.gpm.controller;

import java.util.*;
import java.util.stream.Collectors;

import com.topscomm.basic.exception.MessageException;
import com.topscomm.basic.exception.ServiceException;
import com.topscomm.cbo.pojo.CboUserEntity;
import com.topscomm.cbo.service.impl.CboDeptService;
import com.topscomm.cbo.service.impl.CboUserService;
import com.topscomm.gpm.controller.auto.GpmProjectHistoryControllerAuto;
import com.topscomm.mms.pojo.MmsDeptExtraInfoEntity;
import com.topscomm.pub.util.BaseUtil;
import com.topscomm.pub.util.ConvertUtil;
import com.topscomm.gpm.GpmSystemConst;
import com.topscomm.gpm.pojo.GpmProjectEntity;
import com.topscomm.gpm.pojo.GpmProjectHistoryEntity;
import com.topscomm.gpm.pojo.GpmWfFormEntity;
import com.topscomm.gpm.service.impl.GpmProjectService;
import com.topscomm.gpm.service.impl.GpmWfFormService;
import com.topscomm.tap.common.ParameterCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import com.topscomm.pub.util.StringBufferProxy;
import com.topscomm.pub.util.StringUtil;
import com.topscomm.pub.vo.ResponseResult;

/**
 * @author: wangxinhua
 * @date: 2021-12-06
 * @description:SD项目立项-历史表Controller
 * @modify:
 */
@RestController
@RequestMapping("sd/projectHistory")
public class GpmProjectHistoryController extends GpmProjectHistoryControllerAuto implements IGpmProjectHistoryController {
	@Autowired
	private GpmWfFormService gpmWfFormService;
	@Autowired
	private CboDeptService cboDeptService;
	@Autowired
	private CboUserService cboUserService;
	@Autowired
	protected GpmProjectService gpmProjectService;
	/**
	 * @author: wangxinhua
	 * @date: 2021-12-06
	 * @param paraMap
	 * @return
	 * @description:转换出查询SQL语句
	 * @modify:
	 */
	@Override
	protected String spellListSql(Map<String, Object> paraMap) {
		StringBufferProxy sql = new StringBufferProxy();
		sql.appendSingle(" 1=1 ");
		if (paraMap.containsKey("qry_name")) {
			String value = paraMap.get("qry_name").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and name like '%{0}%' ", value);
		}
		if (paraMap.containsKey("qry_code")) {
			String value = paraMap.get("qry_code").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and code = '{0}' ", value);
		}
		if (paraMap.containsKey("projectid")) {
			String value = paraMap.get("projectid").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and projectid = '{0}' ", value);
		}
		if (paraMap.containsKey("qry_projectcode")) {
			String value = paraMap.get("qry_projectcode").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and projectcode = '{0}' ", value);
		}
		if (paraMap.containsKey("qry_state")) {
			String value = paraMap.get("qry_state").toString();
			if (!StringUtil.isEmpty(value))
				sql.appendSingle(" and state in ({0})", value);
		}
		return sql.toString();
	}

	/**
	 * @author: wangxinhua
	 * @date: 2021-12-06
	 * @param paraMap
	 * @return
	 * @description:转换出查询SQL语句
	 * @modify:
	 */
	@Override
	@GetMapping(value = "/refList")
	public ResponseResult<Object> refList(@RequestParam(required = false) Map<String, Object> paraMap) {
		return super.refList(paraMap);
	}

	/***
	 * @description: 新增和保存功能
	 * @param map
	 * @return
	 * @author: jiangtao1
	 * @date: 2021/11/24 15:32
	 * @modify:
	 */
	@RequestMapping(method = { RequestMethod.POST, RequestMethod.PUT }, value = "doSave")
	public ResponseResult<Object> doSave(@RequestBody(required = false) Map<String, Object> map) {
		try {
			Map<String, Object> resultMap = this.service.doSave(map);
			return ResponseResult.ok(resultMap);
		} catch (Exception e) {
			return handleControllerException(e);
		}
	}

	@RequestMapping(method = { RequestMethod.POST, RequestMethod.PUT }, value = "saveBaseChange")
	public ResponseResult<Object> saveBaseChange(@RequestBody(required = false) Map<String, Object> map) {
		try {
			Map<String, Object> resultMap = this.service.getBaseChangeEntity(map);
			return ResponseResult.ok(resultMap);
		} catch (Exception e) {
			return handleControllerException(e);
		}
	}

	/***
	 * @description: 项目立项变更
	 * @param paraMap
	 * @return
	 * @author: wxh
	 * @date:
	 * @modify:
	 */
	@PutMapping(value = "/projectChangeApproval")
	public ResponseResult<Object> contractSignApproval(@RequestBody(required = false) Map<String, Object> paraMap) {
		try {
			this.service.doProjectChangeApproval(paraMap);
			return ResponseResult.ok("项目立项变更申请提交成功");
		} catch (Exception ex) {
			return handleControllerException(ex);
		}
	}

	@GetMapping(value = "/queryProjectApprovalId")
	public ResponseResult<Object> queryProjectApprovalId(@RequestParam(required = false) Map<String, Object> paraMap) {
		try {
			paraMap = BaseUtil.decodeSecureMap(paraMap);
			String id = ConvertUtil.convertToString(paraMap.get("id"));
			List<String> queryFields = Arrays
					.asList(GpmWfFormEntity.FieldBusinesstype, GpmWfFormEntity.FieldSourceid, GpmWfFormEntity.FieldSourcetype, GpmWfFormEntity.FieldFinalsourcetype,
							GpmWfFormEntity.FieldFinalsourceid, GpmWfFormEntity.FieldFinalversion, GpmWfFormEntity.FieldId);
			Map<String, Object> result = gpmWfFormService.queryFieldsById(id, queryFields);
			Map<String, Object> projectinfo = this.service.queryMapById(ConvertUtil.convertToString(result.get("sourceid")));
			result.put("projectinfo", projectinfo);
			return ResponseResult.ok(result);
		} catch (Exception ex) {
			return handleControllerException(ex);
		}
	}

	/***
	 * @description: 更新立项部分字段
	 * @param map
	 * @return
	 * @author: jiangtao1
	 * @date: 2021/12/4 10:50
	 * @modify:
	 */
	@PutMapping(value = "/updateProjectPartFields")
	public ResponseResult<Object> updateProjectPartFields(@RequestBody(required = false) Map<String, Object> map) {
		try {
			Map<String, Object> resultMap = new HashMap<String, Object>();
			List<String> queryFields = new ArrayList<String>();
			if(map.containsKey("ismobile")) {
				//获取wfform表数据
				GpmWfFormEntity gpmWfFormEntity = gpmWfFormService.queryById(ConvertUtil.convertToString(map.get("id")));
				map.put("id", ConvertUtil.convertToString(gpmWfFormEntity.getSourceid()));
				if(map.containsKey("invitedecisionusername") && !StringUtil.isEmpty(ConvertUtil.convertToString(map.get("invitedecisionusername")))) {
					List<String> invitedUsers =  Arrays.asList(ConvertUtil.convertToString(map.get("invitedecisionusername")).split(","));
					List<String> invitedCodes = Arrays.asList(ConvertUtil.convertToString(map.get("invitedecisionusercode")).split(","));
					// 获取原始单据
					Map<String,Object> originalMap = this.service.queryMapById(ConvertUtil.convertToString(gpmWfFormEntity.getSourceid()));
					List<String> orginalUsers = Arrays.asList(ConvertUtil.convertToString(originalMap.get("decisionusername")).split(","));
					List<String> orginalCodes = Arrays.asList(ConvertUtil.convertToString(originalMap.get("decisionusercode")).split(","));
					// 遍历姓名去重
					List<String> useUserName = new ArrayList<>();
					for (int i=0; i<invitedUsers.size(); i++) {
						if(!orginalUsers.contains(invitedUsers.get(i))) {
							useUserName.add(invitedUsers.get(i));
						}
					}
					// 工号去重
					List<String> useUserCode = new ArrayList<>();
					for (int i=0; i<invitedCodes.size(); i++) {
						if (!orginalCodes.contains(invitedCodes.get(i))) {
							useUserCode.add(invitedCodes.get(i));
						} else {
							throw new ServiceException("邀请人已包含在决策组成员中，请重新选择");
						}
					}
					// 邀请人员
					String users = useUserName.stream().collect(Collectors.joining(","));
					String decisionusername = useUserName.size() > 0 ?
							ConvertUtil.convertToString(originalMap.get("decisionusername")) + "," + users :
							ConvertUtil.convertToString(originalMap.get("decisionusername"));
					// 邀请人员工号
					String codes = useUserCode.size() > 0 ?
							"," + useUserCode.stream().collect(Collectors.joining(",")) + "," : "";
					String decisionusercode = useUserCode.size() > 0 ?
							ConvertUtil.convertToString(originalMap.get("decisionusercode")) + codes.substring(1) :
							ConvertUtil.convertToString(originalMap.get("decisionusercode"));
					map.put("decisionusercode", decisionusercode);
					map.put("decisionusername", decisionusername);
					map.put("invitedecisionusername", users);
					map.put("invitedecisionusercode", codes);
				}
			}
			for (Map.Entry<String, Object> temp : map.entrySet()) {
				if (!GpmProjectEntity.FieldId.equals(temp.getKey()) && (!"ismobile".equals(temp.getKey()))) {
					queryFields.add(temp.getKey());
				}
			}
			this.service.updateFields(map, queryFields);
			return ResponseResult.ok("修改成功");
		} catch (Exception e) {
			return handleControllerException(e);
		}
	}

	/***
	 * @description: 获取决策组成员
	 * @param paraMap
	 * @return
	 * @author: jiangtao1
	 * @date: 2021/11/29 11:35
	 * @modify:
	 */
	@GetMapping("/queryCeo")
	public ResponseResult<Object> queryCeo(
			@RequestParam(required = false) Map<String, Object> paraMap) {
		try {
			StringBufferProxy sql = new StringBufferProxy();
			String managercode = "";
			if (paraMap.containsKey("managercode")) {
				//managercode为项目经理工号
				managercode = ConvertUtil.convertToString(paraMap.get("managercode"));
			} else {
				GpmProjectHistoryEntity entity = this.service.queryById(paraMap.get("projectid").toString());
				managercode = entity.getProjectmanagercode();
			}
			sql.appendSingle("  ID =(SELECT DEPTID from CBOUSER WHERE CODE='{0}') AND ENABLED=1 ", managercode);
			String code = cboDeptService.queryObjectByWhere(sql.toString()).getCode();
			// 获取扩展信息表
			MmsDeptExtraInfoEntity mmsDeptExtraInfoEntity = this.service.queryDeptCommonCode(code);
			sql.clear();
			List<CboUserEntity> list = cboUserService.queryByWhere(sql.toString());
			if (mmsDeptExtraInfoEntity != null) {
				for (CboUserEntity userinfo : list) {
					if (userinfo.getCode().equals(mmsDeptExtraInfoEntity.getProvincemanagercode())) {
						userinfo.setDescription("sdprovince");
						break;
					}
				}
			}
			return ResponseResult.ok(list);
		} catch (Exception e) {
			return handleControllerException(e);
		}
	}

	/**
	 * @author: wudaliang
	 * @date: 2021-03-30
	 * @description: 修改项目级别变更历史字段
	 * @return: com.topscomm.pub.vo.ResponseResult<java.lang.Object>
	 * @modify:
	 */
	@PostMapping(value = "/updateLevelHistory")
	public ResponseResult<Object> updateLevelHistory(@RequestBody(required = false) Map<String, Object> paraMap) {
		try {
			this.service.updateLevelHistory(paraMap);
			return ResponseResult.ok("成功");
		}catch (Exception e){
			throw new MessageException("修改‘项目级别变更历史’字段失败，请联系管理员");
		}
	}

	/***
	 * @description: 加载审批来源id
	 * @param paraMap
	 * @return
	 * @author: jiangtao1
	 * @date: 2021/12/7 20:01
	 * @modify:
	 */
	@Override protected void afterLoad(Map<String, Object> paraMap) {
		super.afterLoad(paraMap);
		String id = ConvertUtil.convertToString(paraMap.get("id"));
		//变更审批sourceid
		StringBufferProxy sqlChange = new StringBufferProxy();
		sqlChange.appendSingle(" finalsourcetype = '{0}' and businesstype = '{1}'  and sourcetype='{2}' and sourceid={3} order by id desc"
				, GpmProjectEntity.tableName, GpmSystemConst.SdApprovalCategory.SdProjectChange, GpmProjectHistoryEntity.tableName, id);
		List<GpmWfFormEntity> wfFormChangeEntities = gpmWfFormService.queryByWhere(sqlChange.toString());
		if (wfFormChangeEntities.size() > 0) {
			paraMap.put("approvalchangeid", wfFormChangeEntities.get(0).getId());
		}
	}

	/***
	 * @description: 获取合同产品信息
	 * @param paraMap
	 * @return
	 * @author: jiangtao1
	 * @date: 2021/11/25 9:35
	 * @modify:
	 */
	@PostMapping(value = "/copyProductInfo")
	public ResponseResult<Object> copyProductInfo(@RequestBody(required = false) Map<String, Object> paraMap) {
		try {
			List<Map<String, Object>> entities = gpmProjectService.copyProductInfo(paraMap);
			return ResponseResult.ok(entities);
		} catch (Exception e) {
			return handleControllerException(e);
		}
	}
}

